package cmw.com.beijingnew.menudetailpager.tabdetailpager;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apkfuns.logutils.LogUtils;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cmw.com.base.MenuDetailBasePager;
import cmw.com.beijingnew.R;
import cmw.com.beijingnew.activity.NewsDetailActivity;
import cmw.com.beijingnew.constant.SysConstant;
import cmw.com.beijingnew.model.NewsModel;
import android.cmw.comw.refreshlistview.RefreshListView;
import cmw.com.utils.CacheUtil;
import cmw.com.utils.JsonUtil;
import cmw.com.beijingnew.model.TopBannerModel;
import cmw.com.utils.StringHandler;

/**
 * 新闻TabDetailPager 详情页面
 * Created by Administrator on 2017/4/23.
 */

public class TabDetailPager extends MenuDetailBasePager {

    /**
     * 用来记录用户已经点击过的新闻的KEY
     */
    public static final String READED_TITLE_ARR = "readed_title_arr";
    private String tabTitle;

    String url = SysConstant.NEWS_LIST_URL;

    private ViewPager viewpager;

    private TextView  tv_title;

    private LinearLayout ll_point_group;

    private RefreshListView listview;

    ImageOptions imageOptions;

    /**
     * 顶部轮播图列表
     */
    List<TopBannerModel> topBannerModels;

    //用来记录上一次页面滑动的位置
    private int prevPostion = 0;
    /**
     * 新闻数据起始页
     */
    private int startPage = 0;
    /**
     * 每页新闻数量
     */
    private int pageNums = 10;
    /**
     * 底部加载更多
     */
    private boolean isLoadMore = false;
    /**
     * 新闻列表
     */
    List<NewsModel> newsList = null;
    /**
     * 新闻列表适配器
     */
    ListItemAdapter newsAdapter = null;
    /**
     * 图片轮播Handler
     */
    private InternalHandler internalHandler;

    public TabDetailPager(Context context, String tabTitle) {
        super(context);
        this.tabTitle = tabTitle;
        //设置当没有图片时，xutils 默认加载的图片
        imageOptions = new ImageOptions.Builder()
                .setSize(DensityUtil.dip2px(120), DensityUtil.dip2px(120))
                .setRadius(DensityUtil.dip2px(5))
                // 如果ImageView的大小不是定义为wrap_content, 不要crop.
                .setCrop(true) // 很多时候设置了合适的scaleType也不需要它.
                // 加载中或错误图片的ScaleType
                //.setPlaceholderScaleType(ImageView.ScaleType.MATRIX)
                .setImageScaleType(ImageView.ScaleType.CENTER_CROP)
                .setLoadingDrawableId(R.drawable.item_default)
                .setFailureDrawableId(R.drawable.item_default)
                .build();
    }

    @Override
    protected View initView() {
        View view = View.inflate(context, R.layout.tab_detail_pager, null);
        listview = (RefreshListView) view.findViewById(R.id.listview);
        View topBannerView = View.inflate(context, R.layout.tab_detail_topbanner,null);

        viewpager = (ViewPager) topBannerView.findViewById(R.id.viewpager);
        tv_title = (TextView) topBannerView.findViewById(R.id.tv_title);
        ll_point_group = (LinearLayout) topBannerView.findViewById(R.id.ll_point_group);
        //listview.addHeaderView(topBannerView);
        listview.addTopBannersView(topBannerView);
        listview.setOnRefreshListenr(new MyOnRefreshListener());
        listview.setOnItemClickListener(new MyOnItemClickListener());
        return view;
    }

    /**
     * ListeView 点击后的新闻标题变灰效果
     */
    class MyOnItemClickListener implements AdapterView.OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            int postion = i-1;
            NewsModel model = newsList.get(postion);
            String title = model.getTitle();
//            Toast.makeText(context,"title="+model.getTitle(),Toast.LENGTH_SHORT).show();
            String readedTitle = CacheUtil.getString(context,READED_TITLE_ARR);
            if(!readedTitle.contains(title)){
                if(!StringHandler.isValidStr(readedTitle)){
                    CacheUtil.putString(context, READED_TITLE_ARR, title);
                }else{
                    CacheUtil.putString(context, READED_TITLE_ARR, readedTitle+","+title);
                }
                //通知Adapter 刷新数据
                newsAdapter.notifyDataSetChanged();
            }
            Intent intent = new Intent(context, NewsDetailActivity.class);
            intent.putExtra("title", model.getTitle());
            intent.putExtra("time",model.getTime());
            intent.putExtra("src",model.getSrc());
            intent.putExtra("pic", model.getPic());
            intent.putExtra("url", model.getUrl());
            intent.putExtra("weburl", model.getWeburl());
            intent.putExtra("content", model.getContent());
            context.startActivity(intent);
        }
    }

    /**
     * ListView 下拉刷新实现类
     */
    class MyOnRefreshListener implements RefreshListView.OnRefreshListener{

        @Override
        public void onPullDownRefresh() {
            startPage++;
            loadDataFromNet(true);
        }

        /**
         * 底部加载更多
         */
        @Override
        public void onLoadMore() {
            Toast.makeText(context,"底部加载更多被回调了",Toast.LENGTH_LONG).show();
            startPage++;
            isLoadMore = true;
            loadDataFromNet(true);
        }
    }

    @Override
    public void initData() {
        super.initData();
        LogUtils.e("tabTitle="+tabTitle);
       loadData();
    }

    private void loadData() {
        String key = url + "&channel="+tabTitle;
        JSONObject jsonData = CacheUtil.getJson(context,key);
        process(jsonData);
        loadDataFromNet(false);
    }

    /**
     * 从网络加载数据
     */
    private void loadDataFromNet(final boolean isPullRefresh) {
        url += "&channel="+tabTitle;
        RequestParams pars = new RequestParams();
        pars.setUri(url);
        pars.addParameter("num", pageNums);
        pars.addParameter("start", startPage);
        x.http().get(pars, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                LogUtil.e("onSuccess.result = "+result);
                JSONObject jsonObj = JsonUtil.convertStrToJSONObj(result);
                CacheUtil.putJson(context, url, jsonObj);
                process(jsonObj);
                if(isPullRefresh) listview.onRefreshFinish(true);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                LogUtil.e("onError.ex = "+ex.getMessage());
                if(startPage > 0) startPage--; //加载新闻失败，让新闻页数还原
                if(isPullRefresh) listview.onRefreshFinish(false);
                if(isLoadMore) isLoadMore = false;
            }

            @Override
            public void onCancelled(CancelledException cex) {
                LogUtil.e("onCancelled.ex = "+cex.getMessage());
            }

            @Override
            public void onFinished() {
                LogUtil.e("onFinished...");
            }
        });
    }

    /**
     * 处理网络JSON数据
     * @param jsonData
     */
    private void process(JSONObject jsonData) {
        if(null == jsonData || jsonData.size() == 0) return;
        int status = jsonData.getInteger("status");
        if(status != 0){
            LogUtil.e("读取["+tabTitle+"]的新闻列表失败，原因："+jsonData.getString("msg"));
            return;
        }
        JSONObject result = jsonData.getJSONObject("result");
        JSONArray list = result.getJSONArray("list");
        LogUtil.e(tabTitle+"的新闻条数："+list.size());
        if(!isLoadMore){//下拉刷新及正常数据加载
            topBannerModels = createTopBanners(list);
            if(null == topBannerModels ||topBannerModels.size() == 0) return;
            //通过 PagerAdapter 加载图片到ViewPager中
            viewpager.setAdapter(new ViewPagerAdatper(topBannerModels));
            //添加 圆点 到线性布局中
            addPointGroup(topBannerModels);
            //默认选中第一个新闻标题
            tv_title.setText(topBannerModels.get(prevPostion).getTitle());

            //监听页面变化，设置红点和文本变化
            viewpager.addOnPageChangeListener(new ViewPagerOnPageChangeListener(topBannerModels));

            newsList = JsonUtil.convertJsonToList(list, NewsModel.class);

            //新闻列表ListView设置适配器
            newsAdapter =  new ListItemAdapter(newsList);
            listview.setAdapter(newsAdapter);
        }else {//滑动到底部加载更多...
            isLoadMore = false;
            List<NewsModel> moreNewsList = JsonUtil.convertJsonToList(list, NewsModel.class);
            if(null == moreNewsList || moreNewsList.size() == 0) return;
            newsList.addAll(moreNewsList);
            newsAdapter.notifyDataSetChanged();
            //listview.setSelection(newsList.size()-1);
        }

        /**-------- 图片自动轮播效果 ---------**/
        //在主线程中发送消息（每隔4秒切换一次ViewPager页面）
        if(null == internalHandler){
            internalHandler = new InternalHandler();
        }
        //先把消息队列所有的消息和回调移除
        internalHandler.removeCallbacksAndMessages(null);
        internalHandler.postDelayed(new MyRunable(), 4000);

    }
    /**
     * 图片轮播Handler
     */
    class InternalHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //切换ViewPager 的下一个页面
            LogUtils.e("currItem ="+viewpager.getCurrentItem()+",banner.size="+topBannerModels.size());
            int item = (viewpager.getCurrentItem() + 1) % topBannerModels.size();
            viewpager.setCurrentItem(item);
            internalHandler.postDelayed(new MyRunable(), 4000);
        }
    }

   public class MyRunable implements Runnable {

        @Override
        public void run() {
            internalHandler.sendEmptyMessage(0);
        }
    }

    /**
     * ListView 适配器
     */
     class ListItemAdapter extends BaseAdapter {
        List<NewsModel> newsList;

        public ListItemAdapter(List<NewsModel> newsList) {
            this.newsList = newsList;
        }

        @Override
        public int getCount() {
            return newsList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder = null;
            if(null == view){
                view = View.inflate(context, R.layout.item_tabdetail_pager, null);
                viewHolder = new ViewHolder();
                viewHolder.iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
                viewHolder.tv_itemTitle = (TextView) view.findViewById(R.id.tv_itemTitle);
                viewHolder.tv_time = (TextView) view.findViewById(R.id.tv_time);
                view.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) view.getTag();
            }
            //根据位置得到对应的新闻数据
            NewsModel model = newsList.get(i);
            x.image().bind(viewHolder.iv_icon, model.getPic(), imageOptions);
            String title = model.getTitle();
            viewHolder.tv_itemTitle.setText(title);
            viewHolder.tv_time.setText(model.getTime());
            String readedTitle = CacheUtil.getString(context,READED_TITLE_ARR);
            if(readedTitle.contains(title)){
                viewHolder.tv_itemTitle.setTextColor(Color.GRAY);
            }else{
                viewHolder.tv_itemTitle.setTextColor(Color.BLACK);
            }
            return view;
        }
    }

    /**
     * ListView Item 的 ViewHolder类
     */
    class ViewHolder{
       ImageView iv_icon;
       TextView tv_itemTitle;
       TextView tv_time;
    }

    /**
     * 添加页面改变事件，以便设置红点和文本变化
     */
    private class ViewPagerOnPageChangeListener implements ViewPager.OnPageChangeListener {
        List<TopBannerModel> topBannerModels;

        public ViewPagerOnPageChangeListener(List<TopBannerModel> topBannerModels) {
            this.topBannerModels = topBannerModels;
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            TopBannerModel model = topBannerModels.get(position);
            tv_title.setText(model.getTitle());
            //将上一次圆设为灰色
            ll_point_group.getChildAt(prevPostion).setEnabled(false);
            //将当前圆设为红色
            ll_point_group.getChildAt(position).setEnabled(true);
            prevPostion = position;
        }

        boolean isDragging = false;

        @Override
        public void onPageScrollStateChanged(int state) {
            if(state == ViewPager.SCROLL_STATE_DRAGGING){//拖拽状态
                isDragging = true;
                //移除消息对列中的消息
                internalHandler.removeCallbacksAndMessages(null);
            }else if(state == ViewPager.SCROLL_STATE_SETTLING){//惯性状态
                isDragging = false;
                //移除消息对列中的消息
                internalHandler.removeCallbacksAndMessages(null);
                //发送新消息
                internalHandler.postDelayed(new MyRunable(), 4000);
            }else if(state == ViewPager.SCROLL_STATE_IDLE){//静止状态
                isDragging = false;
                //移除消息对列中的消息
                internalHandler.removeCallbacksAndMessages(null);
                //发送新消息
                internalHandler.postDelayed(new MyRunable(), 4000);
            }
        }
    }

    /**
     * 添加 圆点 到线性布局中
     * @param topBannerModels
     */
    private void addPointGroup(List<TopBannerModel> topBannerModels) {
        //显示红/灰点
        boolean isFirst = true;
        ll_point_group.removeAllViews();//在添加红点前先移除上一次添加的，以防止重复添加多个
        for(TopBannerModel model : topBannerModels){
            ImageView pointImg = new ImageView(context);
            pointImg.setBackgroundResource(R.drawable.point_selector);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    DensityUtil.dip2px(8),DensityUtil.dip2px(8));
            if(isFirst){
                pointImg.setEnabled(true);
            }else{
                pointImg.setEnabled(false);
                //设置第1个及以后的点与左边的边距为 8 dp
                params.leftMargin = DensityUtil.dip2px(8);
            }
            isFirst = false;
            pointImg.setLayoutParams(params);
            ll_point_group.addView(pointImg);
        }
    }

    /**
     * ViewPager图片适配器
     */
    class ViewPagerAdatper extends PagerAdapter {

        List<TopBannerModel> topBannerModels;

        public ViewPagerAdatper(List<TopBannerModel> topBannerModels) {
            this.topBannerModels = topBannerModels;
        }

        @Override
        public int getCount() {
            return topBannerModels.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return (view == object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            TopBannerModel model = topBannerModels.get(position);
            ImageView imageView = new ImageView(context);
            imageView.setBackgroundResource(R.drawable.home_img_bg);
            //将图片进行拉伸填满ViewPager,处理图片尺寸过小问题
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            viewpager.addView(imageView);
            String picUrl = model.getPicUrl();
            //用 xutil 连网请求图片
            x.image().bind(imageView,picUrl);

            //处理图片自动播放时的触摸事件
            imageView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    switch (motionEvent.getAction()){
                        case MotionEvent.ACTION_DOWN : {//按下时移除所有消息
                            //按下时把消息队列中的所有消息移除
                            internalHandler.removeCallbacksAndMessages(null);
                            break;
                        }case MotionEvent.ACTION_UP : {//松开手时，重新隔4秒轮播图片
                            //按下时把消息队列中的所有消息移除
                            internalHandler.removeCallbacksAndMessages(null);
                            //重新隔4秒发送消息
                            internalHandler.postDelayed(new MyRunable(), 4000);
                            break;
                        }
                    }
                    return true;
                }
            });
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
           container.removeView((View) object);
        }
    }

    /**
     * 取新闻列表中最后三条新闻的图片做为轮播图
     * @param list
     * @return
     */
    private List<TopBannerModel> createTopBanners(JSONArray list) {
        List<TopBannerModel> models = new ArrayList<TopBannerModel>();
        int i = 0;
        for (int index = list.size() - 1; index >= list.size() - 3; index--) {
            JSONObject json = list.getJSONObject(index);
            String title = json.getString("title");
            String pic = json.getString("pic");
            TopBannerModel model = new TopBannerModel();
            model.setTitle(title);
            model.setPicUrl(pic);
            models.add(model);
        }
        return models;

    }
}
